import { words } from "../../../static/js/loveData";
import dayjs from "dayjs";
// 获取应用实例
const app = getApp();

// 初始化数据库
const db = wx.cloud.database();
const uimg = db.collection("uimg");

// pages/word/word.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    openid: '',
    o_openid: '',
    theme: 1,
    hide: false,
    words,
    oneWord: "",
    love_word: [],
    ipt_value: '',
    checkAllWord: true,
    showAddInput: false,

    navHeight: app.globalData.navBarHeight,
    menuHeight: app.globalData.menuHeight,
    menuRight: app.globalData.menuRight,
    menuTop: app.globalData.menuTop,
    screenHeight: app.globalData.screenHeight,
    screenWidth: app.globalData.screenWidth
  },

  getLoveWord(checkOne = true) {
    const that = this;
    const { openid, o_openid } = that.data;
    let { screenHeight, screenWidth } = this.data;
    if (!o_openid) {
      wx.showModal({
        title: "绑定提醒",
        content: "你还没有绑定情侣，是否现在去绑定？",
        complete: (res) => {
          if (res.cancel) {
            wx.navigateBack();
          }
          if (res.confirm) {
            wx.navigateTo({
              url: "/packageMine/pages/invitecode/invitecode",
            });
          }
        },
      });
      return;
    }

    wx.showLoading({
      title: "Loading...",
    });
    that.setData({
      checkAllWord: checkOne
    });
    uimg.where({ _openid: openid }).get({
      success: res => {
        let { love_word } = res.data[0];
        // if (love_word.length != 0) {
        //   love_word.forEach(i => {
        //     let _y = that.random(screenHeight - 100, 100);
        //     let _x = that.random(screenWidth - 100, 100);
        //     i.x = _x;
        //     i.y = _y;
        //   })
        // }
        if (checkOne) {
          if (love_word.length <= 0) {
            that.setData({ love_word: [] });
          } else if (love_word.length > 0 && love_word.length <= 1) {
            that.setData({ love_word: [love_word[0]] });
          } else if (love_word.length > 1 && love_word.length <= 2) {
            that.setData({ love_word: [love_word[0], love_word[1]] });
          } else {
            that.setData({ love_word: [love_word[0], love_word[1], love_word[2]] });
          }
        } else {
          that.setData({ love_word });
        }
      },
      fail: err => { },
      complete: () => {
        wx.hideLoading()
      }
    })
  },

  showAddInput() {
    let { showAddInput } = this.data;
    if (!showAddInput) {
      this.setData({
        showAddInput: true
      })
    } else {
      this.setData({
        showAddInput: false
      })
    }
  },

  handleWord(e) {
    const that = this;
    let { openid, o_openid, ipt_value, checkAllWord } = that.data;
    wx.showLoading({
      title: '发布中...',
    })
    uimg.where({ _openid: o_openid }).get({
      success: res => {
        let { love_word } = res.data[0];
        love_word.unshift({
          title: ipt_value,
          time: dayjs(new Date()).format("YYYY/MM/DD HH:mm:ss"),
          nickname: wx.getStorageSync('nickname'),
          avatarUrl: wx.getStorageSync('avatarUrl'),
          openid
        });
        uimg.where({ _openid: openid }).update({
          data: {
            love_word
          },
          success: res => {
            console.log(res);
            uimg.where({ _openid: o_openid }).update({
              data: {
                love_word
              },
              success: res => {
                that.getLoveWord(checkAllWord);
                that.setData({
                  showAddInput: false,
                  ipt_value: ''
                })
              },
              complete: () => {
                wx.hideLoading();
              }
            })
          }
        })
      },
    })
  },

  checkAllWord(e) {
    const { type } = e.currentTarget.dataset;
    if (type == 'open') {
      this.getLoveWord(false);
      this.setData({
        checkAllWord: false
      })
    } else if (type == 'close') {
      this.getLoveWord(true);
      this.setData({
        checkAllWord: true
      })
    }
  },

  bindinput(e) {
    let ipt_value = e.detail.value;
    this.setData({
      ipt_value
    })
  },

  bindlongpress(e) {
    const that = this;
    const { title } = e.currentTarget.dataset;
    console.log(title);
    wx.setClipboardData({
      data: title,
      success(res) {
        wx.showToast({
          title: '复制成功',
          icon: 'none'
        })
      }
    })
  },

  // 获取每日情话
  getRanWord(arr) {
    wx.showLoading({
      title: "Loading...",
    });
    let { oneWord } = this.data;
    oneWord = arr[Math.floor(Math.random() * arr.length)].wordsList;
    this.setData({ oneWord });
    // console.log(oneWord);
    // wx.showToast({
    //   title: "加载成功",
    //   icon: "success",
    // });
    wx.hideLoading();
  },

  onClose(e) {
    const { position, instance } = e.detail;
    const that = this;
    const { id } = e.currentTarget.dataset;
    const { openid, o_openid, checkAllWord } = that.data;
    switch (position) {
      case 'cell':
        instance.close();
        break;
      case 'right':
        wx.showModal({
          title: '删除提醒',
          content: '确定要删除嘛？',
          complete: (res) => {
            if (res.cancel) {
              instance.close();
            }
            if (res.confirm) {
              uimg.where({ _openid: o_openid }).get({
                success: res => {
                  let { love_word } = res.data[0];
                  love_word = love_word.filter(i => i.time != id);
                  uimg.where({ _openid: openid }).update({
                    data: {
                      love_word
                    },
                    success: res => {
                      console.log(res);
                      uimg.where({ _openid: o_openid }).update({
                        data: {
                          love_word
                        },
                        success: res => {
                          that.getLoveWord(checkAllWord);
                        }
                      })
                    }
                  })
                },
              })
              instance.close();
            }
          }
        })
        break;
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let { words } = this.data;
    this.getRanWord(words);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() { },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const openid = wx.getStorageSync("openid");
    const o_openid = wx.getStorageSync("o_openid");

    this.setData({
      theme: app.globalData.theme,
      hide: app.globalData.switch,
      openid,
      o_openid,
    });

    this.getLoveWord();
  },

  random(max, min) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() { },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() { },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() { },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() { },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() { },
});
